<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addSub()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="getStuInfo(item.id)">删除</button>
            <button @click="bianJi(item, index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      flae: false,
      index:0,
      list: [
        {
          id: 15,
          name: "王宝强",
          age: 25,
          gender: "男",
        },
        {
          id: 27,
          name: "贾乃亮",
          age: 21,
          gender: "男",
        },
        {
          id: 25,
          name: "羽 泉",
          age: 18,
          gender: "女",
        },
      ],
      name: "",
      age: "",
      gender: "",
      id: "",
    };
  },
  methods: {
    // 删除数据
    getStuInfo(id) {
      // console.log(id);
      // 利用filter数组方法筛选出数组中id，点击以后把不是此id的重新推到数组里面
      this.list = this.list.filter((item) => item.id != id);
      // splice数组方法
      //  const newArr =  this.list.toSpilced((item)=>{})
    },

    // 添加数据
    addSub() {
      const obj = {
            id: this.list.length + 202105110758,
            name: this.name,
            age: this.age,
            gender: this.gender,
          }
      if (this.flae) {
        if (this.name && this.age && this.gender) {
          this.list.splice(this.index,1,obj)
          this.name= "";
          this.age= "";
          this.gender= "";
          this.flae=false
        } else {
          alert("请输入正确的格式");
        }
      } else {
        if (this.name && this.age && this.gender) {
          this.list=[...this.list,obj]
          this.name= "";
          this.age= "";
          this.gender= ""
        } else {
          alert("请输入正确的格式");
        }
      }
    },

    // 修改数据
    bianJi(data, index) {
      this.flae = true;
      this.index = index;
      this.name = data.name;
      this.age = data.age;
      this.gender = data.gender;
    },
  },
};
</script>